/**
 * @Title: UserServiceImpl.java
 * @Package org.wk.user.service
 * @Description: TODO【】
 * @author df.w
 * @date 2018年5月3日 下午2:34:31
 * @version V1.0
 */

package org.wk.user.service;

import java.io.File;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.wk.account.dao.SubAccountDao;
import org.wk.account.domain.SubAccount;
import org.wk.account.domain.zhong.SubAccountZhong;
import org.wk.account.enums.AccountType;
import org.wk.account.enums.PaymentType;
import org.wk.account.service.*;
import org.wk.common.dao.SmsDao;
import org.wk.common.domain.Sms;
import org.wk.common.enums.SmsCodeType;
import org.wk.common.jpush.PushService;
import org.wk.core.common.exception.ExceptionCode;
import org.wk.core.common.tool.ExcelUtils;
import org.wk.core.common.tool.HashUtils;
import org.wk.core.common.tool.IDCardUtils;
import org.wk.core.common.tool.RegexUtils;
import org.wk.core.common.view.PageVo;
import org.wk.core.common.view.ResponseVo;
import org.wk.core.db.tool.WebUtils;
import org.wk.core.web.exception.GeneralException;
import org.wk.user.dao.ApplyVipDao;
import org.wk.user.dao.UserDao;
import org.wk.user.dao.UserPromoteRelationDao;
import org.wk.user.domain.ApplyVip;
import org.wk.user.domain.User;
import org.wk.user.domain.UserPromoteRelation;
import org.wk.user.enums.*;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.wk.user.view.UserVo;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName	: UserServiceImpl
 * @Package		：org.wk.user.service
 * @Author df.w
 * @Create Time	：2018年5月3日 下午2:34:31
 * @Description	: 
 */

@Service
public class UserServiceImpl implements UserService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserDao userDao;

	@Autowired
	private SmsDao smsDao;

	@Autowired
	private SubAccountDao subAccountDao;

	@Autowired
	private ApplyVipDao applyVipDao;

	@Autowired
	private UserPromoteRelationDao userPromoteRelationDao;

	@Autowired
	private SubAccountService subAccountService;
	@Autowired
	private SubAccountBaoService baoService;
	@Autowired
	private SubAccountZaiService zaiService;
	@Autowired
	private SubAccountZhongService zhongService;
	@Autowired
	private SubAccountZuanService zuanService;
	@Autowired
	private SubAccountLingService lingService;
	@Autowired
	private SubAccountYuanService yuanService;
	@Autowired
	private LoginTokenService loginTokenService;

	/* (非 Javadoc)
	 * <p>Title: profile</p>
	 * <p>Description: </p>
	 * @return
	 * @see org.wk.user.service.UserService#profile()
	 */
	@Override
	public ResponseVo profile() {
		// TODO Auto-generated method stub
		String userId = WebUtils.getUser().getId();

		Optional<User> userOpt = userDao.findById(userId);
		if (!userOpt.isPresent()) {
			//用户不存在
			return new ResponseVo(ResponseCode.ACCOUNTS_UN_EXIST);
		}

		User user = userOpt.get();

		if (13 > user.getIdentityCode()){
			user.setNextIdentityName(IdentityType.containsCode(user.getIdentityCode()+1).getName());
		}

		return ResponseVo.success().setData(user);
	}


	/* (非 Javadoc)
	 * <p>Title: updateProfile</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.UserService#updateProfile(com.alibaba.fastjson.JSONObject)
	 * @desc:
	 *
	 */
	@Override
	public ResponseVo updateProfile(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		String userId = WebUtils.getUser().getId();
		Optional<User> userOpt = userDao.findById(userId);
		if (!userOpt.isPresent()) {
			return new ResponseVo(ResponseCode.ACCOUNTS_UN_EXIST);
		}
		User user = userOpt.get();
		String weChat = jsonObject.getString("weChat");//昵称
		String userName = jsonObject.getString("userName");//性别码
		boolean isNeedUpdate = false;
		//用户只能修改这几项数据
		if (!Strings.isNullOrEmpty(weChat)) {
			user.setWeChat(weChat);
			isNeedUpdate = true;
		}

		if (!Strings.isNullOrEmpty(userName)) {
			user.setUserName(userName);
			isNeedUpdate = true;
		}

		if (isNeedUpdate) {
			userDao.update(user);
		}

		return ResponseVo.success();
	}


	/* (非 Javadoc)
	 * <p>Title: updateLoginPassword</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.UserService#updateLoginPassword(com.alibaba.fastjson.JSONObject)
	 * @desc:
	 * 	用户直接输入新密码即可，无需输入旧密码
	 */

	@Override
	public ResponseVo updateLoginPassword(JSONObject jsonObject) {
		// TODO Auto-generated method stub
//		String oldPwd = jsonObject.getString("old_password");
		String newPwd = jsonObject.getString("renew_password");
//		if (Strings.isNullOrEmpty(oldPwd)||Strings.isNullOrEmpty(newPwd)) {
//			return new ResponseVo(ResponseCode.PASSWORD_EMPTY);
//		}
		if (Strings.isNullOrEmpty(newPwd)|| newPwd.contains(" ") || newPwd.length() < 6) {
			return new ResponseVo(ResponseCode.PASSWORD_ERROR);
		}
		String userId = WebUtils.getUser().getId();
		Optional<User> userOpt = userDao.findById(userId);
		if (!userOpt.isPresent()) {
			return new ResponseVo(ResponseCode.ACCOUNTS_UN_EXIST);
		}
		User user = userOpt.get();
//		if (!user.getPassword().equals(oldPwd)) {
//			return new ResponseVo(ResponseCode.ACCOUNTS_PASSWORD_ERROR);
//		}
		String salt = UUID.randomUUID().toString();
		user.setSalt(salt);
		user.setPassword(HashUtils.encodePwd(newPwd,salt));
		userDao.update(user);
		return ResponseVo.success();
	}



	/* (非 Javadoc)
	 * <p>Title: verifyIDCard</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.UserService#verifyIDCard(com.alibaba.fastjson.JSONObject)
	 */

	@Override
	public ResponseVo verifyIDCard(JSONObject jsonObject) {
		// TODO Auto-generated method stub

		String realName = jsonObject.getString("real_name");
		String idcardNo = jsonObject.getString("idcard_no");

		if (Strings.isNullOrEmpty(realName)) {
			return new ResponseVo(ResponseCode.REAL_NAME_EMPTY);
		}

		if (Strings.isNullOrEmpty(idcardNo)) {
			return new ResponseVo(ResponseCode.IDCARD_NO_EMPTY);
		}
		//校验身份证号有效性
		if (!IDCardUtils.isValidIdNo(idcardNo)) {
			return new ResponseVo(ResponseCode.IDCARD_NO_ERROR);
		}

		String userId = WebUtils.getUser().getId();
		Optional<User> userOpt = userDao.findById(userId);
		if (!userOpt.isPresent()) {
			return new ResponseVo(ResponseCode.ACCOUNTS_UN_EXIST);
		}
		User user = userOpt.get();
		//如果已经认证过的
		if (IDCardStatus.VERIFIED.getCode().equals(user.getIdcardStatusCode())) {
			return ResponseVo.success();
		}
		//如果处于认证中的
		if (IDCardStatus.VERIFYING.getCode().equals(user.getIdcardStatusCode())) {
			return ResponseVo.success();
		}

		user.setRealName(realName);
		user.setIdcardNo(idcardNo);
		user.setIdcardStatusCode(IDCardStatus.VERIFIED.getCode());
		userDao.update(user);

		return ResponseVo.success();
	}

	/* (非 Javadoc)
	 * <p>Title: verifyVip</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.UserService#verifyIDCard(com.alibaba.fastjson.JSONObject)
	 */
	@Override
	public ResponseVo verifyVip(JSONObject jsonObject) {
		//当前用户id
		String userId = WebUtils.getUser().getId();
		//要审批的申请人id
		String applyId = jsonObject.getString("apply_id");
		ApplyVip applyVip = applyVipDao.findByUserIdAndRelationId(applyId, userId);
		if (null != applyVip){
			applyVip.setRelationStatus(VerifyStatus.FINAL_VERIFY_PASS.getCode());
			if (null == applyVip.getSellerId() || (null != applyVip.getSellerId() && VerifyStatus.FINAL_VERIFY_PASS.getCode().equals(applyVip.getSellerStatus()))){
				//两个都申请通过了,那么修改用户等级
				User user = userDao.getOne(applyId);
				user.setIdentityCode(applyVip.getIdentityCode());
				user.setIdentityName(IdentityType.containsCode(applyVip.getIdentityCode()).getName());
				userDao.update(user);
			}
			applyVipDao.update(applyVip);
			//修改推荐关系状态
			UserPromoteRelation userPromoteRelation = userPromoteRelationDao.findByParentIdAndUserId(userId,applyId);
			userPromoteRelation.setStatus("Y");
			userPromoteRelationDao.update(userPromoteRelation);
		} else {
			//商家审批
			ApplyVip apply2Vip = applyVipDao.findByUserIdAndSellerId(applyId, userId);
			if (null != apply2Vip){
				apply2Vip.setSellerStatus(VerifyStatus.FINAL_VERIFY_PASS.getCode());
				if (VerifyStatus.FINAL_VERIFY_PASS.getCode().equals(apply2Vip.getRelationStatus())){
					//两个都申请通过了,那么修改用户等级
					User user = userDao.getOne(applyId);
					user.setIdentityCode(apply2Vip.getIdentityCode());
					user.setIdentityName(IdentityType.containsCode(apply2Vip.getIdentityCode()).getName());
					userDao.update(user);
				}
				applyVipDao.update(apply2Vip);
				//修改推荐关系状态
				UserPromoteRelation userPromoteRelation = userPromoteRelationDao.findByParentIdAndUserId(userId,applyId);
				userPromoteRelation.setStatus("S");
				userPromoteRelationDao.update(userPromoteRelation);
			} else {
				return ResponseVo.error().setMessage("该申请不存在!");
			}
		}
		return ResponseVo.success();
	}

	/* (非 Javadoc)
	 * <p>Title: verifyVipList</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 * @see org.wk.user.service.UserService#verifyVipList(com.alibaba.fastjson.JSONObject)
	 */
	@Override
	public ResponseVo verifyVipList() {
		//获取普通升级数据
		String userId = WebUtils.getUser().getId();
		List<User> userList = new ArrayList<>();
		User user;
		List<ApplyVip> appList = applyVipDao.findByRelationIdAndRelationStatus(userId,VerifyStatus.WAIT_VERIFY.getCode());
		if (null != appList && 0 < appList.size()){
			for (ApplyVip applyVip : appList){
				user = userDao.getOne(applyVip.getUserId());
				user.setNextIdentityName(IdentityType.containsCode(user.getIdentityCode()+1).getName());
				userList.add(user);
			}
		}
		List<ApplyVip> app2List = applyVipDao.findBySellerIdAndSellerStatus(userId,VerifyStatus.WAIT_VERIFY.getCode());
		if (null != app2List && 0 < app2List.size()){
			for (ApplyVip applyVip : app2List){
				user = userDao.getOne(applyVip.getUserId());
				user.setNextIdentityName(IdentityType.containsCode(user.getIdentityCode()+1).getName());
				userList.add(user);
			}
		}
		if (0 < userList.size()){
			return ResponseVo.success().setData(userList);
		}
		return ResponseVo.success();
	}
	/* (非 Javadoc)
	 * <p>Title: verifyVipPassList</p>
	 * <p>Description: </p>
	 * @return
	 * @see org.wk.user.service.UserService#verifyVipList(com.alibaba.fastjson.JSONObject)
	 */
	@Override
	public ResponseVo verifyVipPassList() {
		//获取普通升级数据
		String userId = WebUtils.getUser().getId();
		List<User> userList = new ArrayList<>();
		User user;
		List<ApplyVip> appList = applyVipDao.findByRelationIdAndRelationStatus(userId,VerifyStatus.FINAL_VERIFY_PASS.getCode());
		if (null != appList && 0 < appList.size()){
			for (ApplyVip applyVip : appList){
				user = userDao.getOne(applyVip.getUserId());
				user.setNextIdentityName(IdentityType.containsCode(user.getIdentityCode()+1).getName());
				userList.add(user);
			}
		}
		List<ApplyVip> app2List = applyVipDao.findBySellerIdAndSellerStatus(userId,VerifyStatus.FINAL_VERIFY_PASS.getCode());
		if (null != app2List && 0 < app2List.size()){
			for (ApplyVip applyVip : app2List){
				user = userDao.getOne(applyVip.getUserId());
				user.setNextIdentityName(IdentityType.containsCode(user.getIdentityCode()+1).getName());
				userList.add(user);
			}
		}
		if (0 < userList.size()){
			return ResponseVo.success().setData(userList);
		}
		return ResponseVo.success();
	}

	/* (非 Javadoc)
	 * <p>Title: applyForVip</p>
	 * <p>Description: </p>
	 * @param jsonObject
	 * @return
	 */
	@Override
	public ResponseVo applyForVip() {
		String userId = WebUtils.getUser().getId();
		User user = userDao.getOne(userId);
		//获取申请等级
		//获取用户当前状态,只能申请比自己高一级用户,13级封顶
		int userLv = user.getIdentityCode();
		//判断是否有正在审核中或初审中
		ApplyVip apply = applyVipDao.findByUserIdAndVerifyStatus(userId,VerifyStatus.WAIT_VERIFY.getCode());
		if (null != apply){
			return ResponseVo.error("正在审核中!");
		}
		if (0 == userLv){
			//普通会员升级为一星会员,获取推荐人及上面五星用户名单
			String referralId = user.getReferralCode();
			//判断推荐人是否为5,9,13星用户
			User fUser = userDao.getOne(referralId);
			String fiveId = "";
			if (5 >= fUser.getIdentityCode()){
				fiveId = userPromoteRelationDao.findByUserIdAndRelationship5(userId).getParentId();
			} else if (9 >= fUser.getIdentityCode() && 5 < fUser.getIdentityCode()){
				fiveId = userPromoteRelationDao.findByUserIdAndRelationship9(userId).getParentId();
			} else if (13 >= fUser.getIdentityCode()){
				fiveId = userPromoteRelationDao.findByUserIdAndRelationship13(userId).getParentId();
			}
			//添加到申请列表
			ApplyVip av = new ApplyVip();
			av.setUserId(user.getId());
			av.setIdentityCode(userLv+1);
			av.setIdentityName(IdentityType.containsCode(userLv+1).getName());
			av.setRelationId(referralId);
			av.setRelationStatus(VerifyStatus.WAIT_VERIFY.getCode());
			av.setSellerId(fiveId);
			av.setSellerStatus(VerifyStatus.WAIT_VERIFY.getCode());
			applyVipDao.saveOrUpdate(av);
		} else if (1 == userLv){
			//一星升级二星,需要判断自身团队内有三名一星用户
			Integer count = userPromoteRelationDao.findByParentIdAndRelationship(userId);
			if (3 <= count){
				//满足条件后往上找到最近的二星用户
				String referralId = userPromoteRelationDao.findByUserIdAndRelationship(userId,2).getParentId();
				ApplyVip av = new ApplyVip();
				av.setUserId(user.getId());
				av.setIdentityCode(userLv+1);
				av.setIdentityName(IdentityType.containsCode(userLv+1).getName());
				av.setRelationId(referralId);
				av.setRelationStatus(VerifyStatus.WAIT_VERIFY.getCode());
				applyVipDao.saveOrUpdate(av);
			} else {
				//条件不符合
				int num = count;
				return ResponseVo.error("需要推广3名一钻及以上用户,当前推广一钻及以上用户数量为:"+num);
			}
		} else if ((1 < userLv && 4 > userLv) || (4 < userLv && 8 > userLv) || (8 < userLv && 12 > userLv)){
			//3.4星升级只需要往上找一人申请即可
			String referralId = userPromoteRelationDao.findByUserIdAndRelationship(userId,userLv + 1).getParentId();
			ApplyVip av = new ApplyVip();
			av.setUserId(user.getId());
			av.setIdentityCode(userLv+1);
			av.setIdentityName(IdentityType.containsCode(userLv+1).getName());
			av.setRelationId(referralId);
			av.setRelationStatus(VerifyStatus.WAIT_VERIFY.getCode());
			applyVipDao.saveOrUpdate(av);
		} else if (4 == userLv){
			//四星升五星需要同时向九星用户申请,需要团队中有81名一星及以上用户
			Integer count = userPromoteRelationDao.findByParentIdAndRelationship(userId);
			if (81 <= count){
				String referralId = userPromoteRelationDao.findByUserIdAndRelationship(userId,userLv + 1).getParentId();
				String fiveId = userPromoteRelationDao.findByUserIdAndRelationship9(userId).getParentId();
				//添加到申请列表
				ApplyVip av = new ApplyVip();
				av.setUserId(user.getId());
				av.setIdentityCode(userLv+1);
				av.setIdentityName(IdentityType.containsCode(userLv+1).getName());
				av.setRelationId(referralId);
				av.setRelationStatus(VerifyStatus.WAIT_VERIFY.getCode());
				av.setSellerId(fiveId);
				av.setSellerStatus(VerifyStatus.WAIT_VERIFY.getCode());
				applyVipDao.saveOrUpdate(av);
			} else {
				//条件不符合
				int num = count;
				return ResponseVo.error("需要推广81名一钻及以上用户,当前推广一钻及以上用户数量为:"+num);
			}
		} else if (8 == userLv){
			//八星升九星需要同时向十三星用户申请,需要团队中有81名一星及以上用户
			Integer count = userPromoteRelationDao.findByParentIdAndRelationship(userId);
			if (199 <= count){
				String referralId = userPromoteRelationDao.findByUserIdAndRelationship(userId,userLv + 1).getParentId();
				String fiveId = userPromoteRelationDao.findByUserIdAndRelationship(userId,13).getParentId();
				//添加到申请列表
				ApplyVip av = new ApplyVip();
				av.setUserId(user.getId());
				av.setIdentityCode(userLv+1);
				av.setIdentityName(IdentityType.containsCode(userLv+1).getName());
				av.setRelationId(referralId);
				av.setRelationStatus(VerifyStatus.WAIT_VERIFY.getCode());
				av.setSellerId(fiveId);
				av.setSellerStatus(VerifyStatus.WAIT_VERIFY.getCode());
				applyVipDao.saveOrUpdate(av);
			} else {
				//条件不符合
				int num = count;
				return ResponseVo.error("需要推广199名一钻及以上用户,当前推广一钻及以上用户数量为:"+num);
			}
		} else if (12 == userLv){
			String referralId = userPromoteRelationDao.findByUserIdAndRelationship(userId,userLv+1).getParentId();
			//添加到申请列表
			ApplyVip av = new ApplyVip();
			av.setUserId(user.getId());
			av.setIdentityCode(userLv+1);
			av.setIdentityName(IdentityType.containsCode(userLv+1).getName());
			av.setRelationId(referralId);
			av.setRelationStatus(VerifyStatus.WAIT_VERIFY.getCode());
			applyVipDao.saveOrUpdate(av);
		}
		return ResponseVo.success();

	}

	@Override
	public PageVo queryPage(Map<String, Object> params) {
		String userName = (String)params.get("userName");
		String mobileNumber = (String)params.get("mobileNumber");
		String startDate = (String) params.get("startDate");
		String endDate = (String)params.get("endDate");
		String identity = (String)params.get("identity");
		String temp = (String)params.get("page");
		Integer pageNo = temp==null?0:Integer.parseInt(temp)-1;
		temp = (String) params.get("limit");
		Integer pageSize = temp==null?10:Integer.parseInt(temp);

		User user = new User();
		user.setUserName(userName);
		Page<User> page = userDao.findAll(new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
				if(!StringUtils.isEmpty(userName)){
					list.add(criteriaBuilder.like(root.get("userName").as(String.class), "%"+userName+"%"));
				}
				if (!StringUtils.isEmpty(mobileNumber)){
					list.add(criteriaBuilder.like(root.get("mobileNumber").as(String.class),"%"+mobileNumber+"%"));
				}
				if (!StringUtils.isEmpty(startDate)){
					list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), org.wk.core.common.tool.StringUtils.strToDate(startDate)));
				}
				if (!StringUtils.isEmpty(endDate)){
					list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), org.wk.core.common.tool.StringUtils.strToDate(endDate)));
				}
				if (!StringUtils.isEmpty(identity)){
					list.add(criteriaBuilder.equal(root.get("identityCode"), identity));
				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		}, PageRequest.of(pageNo, pageSize, new Sort(Sort.Direction.DESC, "createTime")));

		List<UserVo> userVos = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(User User : page.getContent()){
			UserVo userVo = new UserVo();
			BeanUtils.copyProperties(User,userVo);
			userVo.setCreateTime(sdf.format(User.getCreateTime()));
			if (null != userVo.getReferralCode()){
				User referralUser = userDao.getOne(userVo.getReferralCode());
				userVo.setReferralName(referralUser.getUserName());
				userVo.setReferralTel(referralUser.getMobileNumber());
			}
			userVos.add(userVo);
		}
		PageVo pageVo = new PageVo<UserVo>();
		pageVo.setTotal(page.getTotalElements());
		pageVo.setPageNo(++pageNo);
		pageVo.setPageSize(pageSize);
		pageVo.setResult(userVos);
		pageVo.setTotalPages(page.getTotalPages());
		return pageVo;
	}

	@Override
	public ResponseVo queryUserDetailById(String id) {
		Optional<User> user = userDao.findById(id);
		UserVo userVo = new UserVo();
		ResponseVo responseVo = ResponseVo.success();
		BeanUtils.copyProperties(user.get(),userVo);
		responseVo.addAttribute("user",userVo);
		return responseVo;
	}

	@Override
	public List<User> getAllByParams(Map<String, Object> params) {
		String mobileNumber = (String)params.get("mobileNumber");

		User user = new User();
		user.setMobileNumber(mobileNumber);
		List<User> list = userDao.findAll(new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
				if(null!=user.getMobileNumber()&&!"".equals(user.getMobileNumber())){
					list.add(criteriaBuilder.like(root.get("mobileNumber").as(String.class), "%"+user.getMobileNumber()+"%"));
				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		});
		return list;
	}


	/*
	 * @Description 获取用户VIP申请状态
	 * @param
	 * @author ZhaoPing'an
	 * @Date 2018/6/22 12:13
	 */
	@Override
	public ResponseVo findVipApplyStatus() {
		String userId = WebUtils.getUser().getId();
		ApplyVip apply = applyVipDao.findByUserIdAndVerifyStatus(userId,VerifyStatus.WAIT_VERIFY.getCode());
		Map<String,Object> result = new HashMap<>();
		if (null == apply){
			//如果没有正在申请的订单直接返回页面
			return ResponseVo.success();
		} else {
			//如果有正在申请的,把商家信息进行展示
			User relationUser = userDao.getOne(apply.getRelationId());
			result.put("relationUser",relationUser);
			if (null != apply.getSellerId()){
				User sellerUser = userDao.getOne(apply.getSellerId());
				result.put("sellerUser",sellerUser);
			}
		}
		return ResponseVo.success().setData(result);
	}

	/*
	 * @description 冻结用户
	 * @param
	 * @author ZhaoPing'an
	 * @date 2018/7/26 14:26
	 */
	@Override
	public ResponseVo freezeUser(String id) {
		User user = userDao.getOne(id);
		if (!user.getStatus().equals(UserStatus.NORMAL.getCode())){
			throw new GeneralException(ExceptionCode.ex_base_001);
		}
		user.setStatus(UserStatus.FREEZE.getCode());
		userDao.update(user);
		loginTokenService.deleteToken(user.getId());
		return ResponseVo.success();
	}

	/*
	 * @description 用户解冻
	 * @param
	 * @author ZhaoPing'an
	 * @date 2018/7/26 14:26
	 */
	@Override
	public ResponseVo unFreezeUser(String id) {
		User user = userDao.getOne(id);
		if (!user.getStatus().equals(UserStatus.FREEZE.getCode())){
			throw new GeneralException(ExceptionCode.ex_base_001);
		}
		user.setStatus(UserStatus.NORMAL.getCode());
		userDao.update(user);
		return ResponseVo.success();
	}

	/*
	 * @description 获取导出用户数据
	 * @param
	 * @author ZhaoPing'an
	 * @date 2018/7/26 15:03
	 */
	@Override
	public List<Object[]> exportUsers(Map<String, Object> params,int size) {
		List<User> seqsData = userDao.findAll();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Object[]>  datas = new ArrayList<Object[]>();
		for (int i = 0; i < seqsData.size(); i++) {
			User data = seqsData.get(i);
			Object[] rowData = new Object[size];
			rowData[0] = i;
			if (StringUtils.isEmpty(seqsData.get(i).getRealName())){
				rowData[1] = "  ";
			} else {
				rowData[1] = seqsData.get(i).getRealName();
			}
			rowData[2] = seqsData.get(i).getNickName();
			rowData[3] = seqsData.get(i).getSexName();
			rowData[4] = seqsData.get(i).getMobileNumber();
			rowData[5] = seqsData.get(i).getIdentityName();
			if (StringUtils.isEmpty(seqsData.get(i).getIdcardNo())){
				rowData[6] = "  ";
			} else {
				rowData[6] = seqsData.get(i).getIdcardNo();
			}
			if (StringUtils.isEmpty(seqsData.get(i).getReferralCode())){
				rowData[7] = "  ";
			} else {
				rowData[7] = seqsData.get(i).getReferralCode();
			}
			rowData[8] = sdf.format(seqsData.get(i).getCreateTime());
			datas.add(rowData);

		}
		/*HSSFWorkbook workbook = ExcelUtils.getHSSFWorkbook("鲸拍用户表",rowsName,datas);
		File path = new File("D:"+ File.separator + "seqs" );
		if (!path.exists()){
			path.mkdir();
		}
		String fileName = "users"+ new LocalDate().toString("yyyyMMdd") +".xls";
		File file = new File(path+File.separator+fileName);
		if (!file.exists()){
			file.createNewFile();
		}*/
		return datas;
	}

	@Override
	public User findUserInfo(String id) {
		return userDao.getOne(id);
	}

	/*
	 * @description 设置二级密码
 	 * @param
	 * @author ZhaoPing'an
	 * @date 2018/8/10 10:14
	 */
	@Override
	public ResponseVo settingLevelTwoPassword(JSONObject jsonObject) {
		String mobileNumber = jsonObject.getString("mobile_number");
		// 校验手机号
		if (Strings.isNullOrEmpty(mobileNumber)||!RegexUtils.checkMobileNum(mobileNumber)) {
			return new ResponseVo(ResponseCode.MOBILE_NUMBER_ERROR);
		}
		//判断该用户是否存在
		User user = userDao.findByMobileNumber(mobileNumber);
		if (null==user) {
			return new ResponseVo(ResponseCode.ACCOUNTS_UN_EXIST);
		}
		String level2Password = jsonObject.getString("levelTwoPassword");
		String confirmLevel2Password = jsonObject.getString("confirmLevelTwoPassword");
		// 判断密码输入是否符合规则
		if (Strings.isNullOrEmpty(level2Password)|| level2Password.contains(" ") || level2Password.length() < 6
			|| Strings.isNullOrEmpty(confirmLevel2Password)|| confirmLevel2Password.contains(" ") || confirmLevel2Password.length() < 6	) {
			return new ResponseVo(ResponseCode.PASSWORD_ERROR);
		}
		// 判断两次输入是否相同
		if (!level2Password.equals(confirmLevel2Password)){
			return new ResponseVo(ResponseCode.ENTERED_PASSWORD_DIFFER);
		}
		// 验证码校验
		String smsCode = jsonObject.getString("smsCode");
		if (Strings.isNullOrEmpty(smsCode)) {
			return new ResponseVo(ResponseCode.SMS_CODE_EMPTY);
		}
		Sms sms = smsDao.findByMobileNumberAndSmsCodeTypeGreaterThanExpireTimeLimit1(mobileNumber,SmsCodeType.SETTING_LEVEL_TWO_PASSWORD.getCode(),new Date());
		if (sms == null || !smsCode.equals(sms.getSmsCode())) {
			return new ResponseVo(ResponseCode.SMS_CODE_ERROR);
		}
		user.setTwoLevelPassword(HashUtils.getSHA256Str(level2Password));
		userDao.update(user);
		return ResponseVo.success();
	}

	/*
	 * @description 修改二级密码
	 * @param
	 * @author ZhaoPing'an
	 * @date 2018/8/10 10:03
	 */
	@Override
	public ResponseVo updateLevelTwoPassword(JSONObject jsonObject) {
		String userId = WebUtils.getUser().getId();
		User user = userDao.getOne(userId);
		String old = jsonObject.getString("oldLevelTwoPassword");
		String newLevelTwoPassword = jsonObject.getString("levelTwoPassword");
		String confirm = jsonObject.getString("confirmLevelTwoPassword");
		// 校验旧密码
		if (Strings.isNullOrEmpty(old) || !HashUtils.getSHA256Str(old).equals(user.getTwoLevelPassword())){
			return new ResponseVo(ResponseCode.OLD_PASSWORD_ERROR);
		}
		// 判断密码输入是否符合规则
		if (Strings.isNullOrEmpty(newLevelTwoPassword)|| newLevelTwoPassword.contains(" ") || newLevelTwoPassword.length() < 6
				|| Strings.isNullOrEmpty(confirm)|| confirm.contains(" ") || confirm.length() < 6	) {
			return new ResponseVo(ResponseCode.PASSWORD_ERROR);
		}
		// 两次密码输入是否一致
		if (!newLevelTwoPassword.equals(confirm)){
			return new ResponseVo(ResponseCode.ENTERED_PASSWORD_DIFFER);
		}
		// 设置新的二级密码
		user.setTwoLevelPassword(HashUtils.getSHA256Str(newLevelTwoPassword));
		userDao.update(user);
		return ResponseVo.success();
	}

	/*
	 * @description PC修改用户信息
	 * @param
	 * @author ZhaoPing'an
	 * @date 2018/8/13 10:46
	 */
	@Transactional
	@Override
	public ResponseVo updateUserDetailById(UserVo userVo) {
		User user = userDao.getOne(userVo.getId());
		ResponseVo responseVo = new ResponseVo();
		if (!RegexUtils.checkMobileNum(userVo.getMobileNumber()) || Strings.isNullOrEmpty(userVo.getMobileNumber())){
			return ResponseVo.error("手机号输入不合法");
		}
		if (Strings.isNullOrEmpty(userVo.getId())) {
			throw new GeneralException("系统错误");
		}
		if (!userVo.getMobileNumber().equals(user.getMobileNumber())){
			User userInfo = userDao.findByMobileNumber(userVo.getMobileNumber());
			if (null!= userInfo){
				return ResponseVo.error("手机号已经存在");
			}
		}
		user.setMobileNumber(userVo.getMobileNumber());
		user.setRealName(userVo.getRealName());
		user.setWeChat(userVo.getWeChat());
		user.setIdentityName(IdentityType.containsCode(userVo.getIdentityCode()).getName());
		user.setIdentityCode(userVo.getIdentityCode());
		userDao.update(user);
		/*String userId = userVo.getId();
		baoService.updateBaoAccount(userVo.getBao(),userId);
		zaiService.updateZaiAccount(userVo.getZai(),userId);
		zuanService.updateZuanAccount(userVo.getZuan(),userId);
		zhongService.updateZhongAccount(userVo.getZhong(),userId);
		yuanService.updateYuanAccount(userVo.getYuan(),userId);
		lingService.updateLingAccount(userVo.getLing(),userId);*/

		return ResponseVo.success();
	}


}
